package main.java.search;

/**
 * @Author: 郑国荣
 * @Date: 2023-10-10-20:58
 * @Description:
 */
public class Search {

    //递归
    public int binarySearch(int[] arr,int left,int right,int target){
        if(arr[right]>target || arr[left]<target || left>right) return -1;

        int mid = left+(right-left)/2;
        if(arr[mid] > target){
            return binarySearch(arr,left,mid-1,target);
        }else if(arr[mid] < target){
            return binarySearch(arr,mid+1,right,target);
        }
        else return mid;
    }
    //非递归
    public int binarySearch(int[] arr,int target,int length){
        int left = 0,right = length-1;
        if(target<arr[right] || target>arr[left] || right<0) return -1;
        while(left<=right){
            int mid = left+(right-left)/2;
            if(target<arr[mid]){
                right = mid-1;
            }else if(target>arr[mid]){
                left = mid+1;
            }else if(target==arr[mid]){
                return mid;
            }
        }
        return -1;
    }
}
